package com.mall.order.services;

import com.mall.order.OrderCoreService;
import com.mall.order.biz.TransOutboundInvoker;
import com.mall.order.biz.context.AbsTransHandlerContext;
import com.mall.order.biz.factory.OrderProcessPipelineFactory;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.constants.OrderConstants;
import com.mall.order.dal.entitys.Order;
import com.mall.order.dal.entitys.OrderItem;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dal.persistence.OrderShippingMapper;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.*;
import com.mall.order.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 *  ciggar
 * create-date: 2019/7/30-上午10:05
 */
@Slf4j
@Component
@Service(cluster = "failfast")
public class OrderCoreServiceImpl implements OrderCoreService {

	@Autowired
	OrderMapper orderMapper;

	@Autowired
	OrderItemMapper orderItemMapper;

	@Autowired
	OrderShippingMapper orderShippingMapper;

	@Autowired
	StockMapper stockMapper;

	@Autowired
    OrderProcessPipelineFactory orderProcessPipelineFactory;


	/**
	 * 创建订单的处理流程
	 *
	 * @param request
	 * @return
	 */
	@Override
	public CreateOrderResponse createOrder(CreateOrderRequest request) {
		CreateOrderResponse response = new CreateOrderResponse();
		try {
			//创建pipeline对象
			TransOutboundInvoker invoker = orderProcessPipelineFactory.build(request);

			//启动pipeline
			invoker.start(); //启动流程（pipeline来处理）

			//获取处理结果
			AbsTransHandlerContext context = invoker.getContext();

			//把处理结果转换为response
			response = (CreateOrderResponse) context.getConvert().convertCtx2Respond(context);
		} catch (Exception e) {
			log.error("OrderCoreServiceImpl.createOrder Occur Exception :" + e);
			ExceptionProcessorUtils.wrapperHandlerException(response, e);
		}
		System.out.println("创建订单成功后的订单id"+response.getOrderId());
		return response;
	}

	@Override
	public DeleteOrderResponse deleteOrder(DeleteOrderRequest deleteOrderRequest) {
		//根据订单id删除订单信息
		String orderId = deleteOrderRequest.getOrderId();
		//如果订单为已付款，或已发货状态，不能删除，如果未付款，或已完成可以删除订单
        //先实现简单删除功能
		int i = orderMapper.deleteByPrimaryKey(orderId);
		//给返回值赋值
		OrderRetCode success = OrderRetCode.SUCCESS;
		DeleteOrderResponse deleteOrderResponse = new DeleteOrderResponse();
		deleteOrderResponse.setCode(success.getCode());
		deleteOrderResponse.setMsg(success.getMessage());
		//先修改订单商品表的状态，并根据查询出的item_id查询库存表
		List<OrderItem> orderItems = orderItemMapper.queryByOrderId(orderId);
        //修改库存信息
		for (OrderItem orderItem : orderItems) {
			Stock stock = stockMapper.selectByPrimaryKey(orderItem.getItemId());
			stock.setStockCount(stock.getStockCount()+orderItem.getNum());
			stock.setLockCount(stock.getLockCount()-orderItem.getNum());
			stockMapper.updateStock(stock);
		}
		//如果库存表修改成功，修改订单商品表中信息
		orderItemMapper.updateStockStatus(2,orderId);

		if(i<1){
				throw new RuntimeException("删除订单失败异常");
		}
		return deleteOrderResponse;
	}

	@Override
	public CancelOrderResponse cancelOrder(CancelOrderRequest cancelOrderRequest) {
		cancelOrderRequest.requestCheck();
		String orderId = cancelOrderRequest.getOrderId();
		//检查状态是否已付款，如果已付款先执行退款操作

		//如果状态为已发货，则订单取消失败

		//先修改订单商品表的状态，并根据查询出的item_id查询库存表
		List<OrderItem> orderItems = orderItemMapper.queryByOrderId(orderId);
		//修改库存信息
		for (OrderItem orderItem : orderItems) {
			Stock stock = stockMapper.selectByPrimaryKey(orderItem.getItemId());
			if(stock!=null) {
				stock.setStockCount(stock.getStockCount() + orderItem.getNum());
				stock.setLockCount(stock.getLockCount() - orderItem.getNum());
				stockMapper.updateStock(stock);
			}
		}
		//如果库存表修改成功，修改订单商品表中信息
		orderItemMapper.updateStockStatus(2,orderId);
		//修改订单状态为交易失败
        Integer i = orderMapper.updateOrderStatusByOrderId(orderId);
        if(i<1){
        	throw new RuntimeException("订单取消异常");
		}
		OrderRetCode success = OrderRetCode.SUCCESS;
		CancelOrderResponse cancelOrderResponse = new CancelOrderResponse();
        cancelOrderResponse.setCode(success.getCode());
        cancelOrderResponse.setMsg(success.getMessage());
        return cancelOrderResponse;
	}

}
